/*
Copyright 2021 LuJun

Permission is hereby granted, free of charge, to any person obtaining a copy 
of this software and associated documentation files (the "Software"), to deal 
in the Software without restriction, including without limitation the rights 
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 
copies of the Software, and to permit persons to whom the Software is furnished 
to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in 
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL 
THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/

import { Component, _decorator, Node, director, game } from 'cc';
const { ccclass } = _decorator;

const TAG = 'lcc/core/timer.ts';

/**
 * 定时器节点名称
 */
const TIMER_NODE_NAME = 'lcc-Timer';

/**
 * @zh
 * 定时器组件，不用主动挂载
 */
@ccclass('lcc/private/Timer')
class TimerComponent extends Component {}

/**
 * @zh
 * 定时器类
 */
class Timer {
    /**
     * @zh
     * 单例对象
     */
    private static _instance: Timer = null!;

    /**
     * @zh
     * 获得单例对象
     */
    static get instance() {
        if (Timer._instance === null) {
            Timer._instance = new Timer();
        }
        return Timer._instance;
    }

    /**
     * 构造函数
     */
    private constructor() {}

    /**
     * @zh
     * 定时器对应节点
     */
    private _node: Node = null;

    /**
     * @zh
     * 定时器对应组件
     */
    private _component: TimerComponent = null;

    /**
     * 获得定时器组件
     */
    private get component() {
        if (!this._component) {
            this._node = new Node(TIMER_NODE_NAME);
            director.getScene().addChild(this._node);
            game.addPersistRootNode(this._node);
            this._component = this._node.addComponent(TimerComponent);
        }
        return this._component;
    }

    /**
     * @zh
     * 开始定时器
     *
     * @param callback 回调函数
     * @param interval 以秒为单位的时间间隔，如果后面没有参数则为开始延时
     * @param repeat 重复次数
     * @param delay 开始延时
     */
    schedule(callback: () => void, interval?: number, repeat?: number, delay?: number) {
        this.component.schedule(callback, interval, repeat, delay);
    }

    /**
     * @zh
     * 开始单次定时器
     *
     * @param callback 回调函数
     * @param delay 开始延时, 为零表示下一帧立即执行
     */
    scheduleOnce(callback: () => void, delay?: number) {
        this.component.scheduleOnce(callback, delay);
    }

    /**
     * @zh
     * 取消定时器
     *
     * @param callback 回调函数
     */
    unschedule(callback: () => void) {
        this.component.unschedule(callback);
    }

    /**
     * @zh
     * 当下一帧的回调
     */
    toNextFrame() {
        return new Promise<void>((resolve) => {
            this.component.scheduleOnce(resolve);
        });
    }

    /**
     * @zh
     * 睡眠指定时间
     *
     * @param time 时间，秒
     */
    sleepTime(time: number, doAsync = false) {
        return new Promise<void>((resolve) => {
            this.component.scheduleOnce(resolve, time);
        });
    }
}

/**
 * 定时器对象
 */
export const timer = Timer.instance;
